package com.fjp.heartguard.viewmodel

import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.base.HTBaseViewModel
import com.fjp.heartguard.app.data.bean.CredentialFile
import com.fjp.heartguard.app.data.bean.UserInfo
import com.fjp.heartguard.app.network.HttpRequestCoroutine
import com.fjp.heartguard.app.util.DateTimeUtil
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.state.ResultState
import okhttp3.MultipartBody

class UserinfoViewModel : HTBaseViewModel() {
    var updateImageFailed = MutableLiveData<Boolean>()
    var updatecertificaterAdapter = MutableLiveData<Boolean>()
    val userInfo = ObservableField<UserInfo>()
    val address = MutableLiveData<String>("")

    var saveResult = MutableLiveData<ResultState<String>>()
    fun saveInfo() {
        request({
            HttpRequestCoroutine.saveInfo(userInfo.get()!!)
        }, saveResult, true, "正在保存信息")

    }

    fun updateAvatar(body: MultipartBody.Part, isAvatar: Boolean, name: String) {
        requestNoCheck({ HttpRequestCoroutine.uploadImg(body) }, {
            //请求成功 自己拿到数据做业务需求操作
            if (it.status == "success") {
                val inof = userInfo.get()
                if (isAvatar) {
                    inof?.profile = it.data
                    userInfo.set(inof)
                    userInfo.notifyChange()
                } else {
                    if(inof?.credential_files==null){
                        inof?.credential_files = mutableListOf()
                    }
                    inof?.credential_files?.add(CredentialFile(it.data, name, DateTimeUtil.formatDate(System.currentTimeMillis(), DateTimeUtil.DATE_PATTERN_SS)))
                    userInfo.set(inof)
                    userInfo.notifyChange()
                    updatecertificaterAdapter.postValue(true)
                }
            } else {
                updateImageFailed.value = true
            }
        }, {
            updateImageFailed.value = true
        }, true, "正在上传图像...")
    }
}